<template>
	<view style="overflow: hidden;min-height: 100%; background-color: #f8f8f8;">
		<!-- 导航栏 -->
		<order-header class="custom-navbar" title="订单详情" 
			:status="statusInfo.status" 
			:image="statusInfo.image"
			:bt-text="statusInfo.btText" 
			:expire="expire" 
			:isPayOrder="true" :paymentMethod="info.paymentMethod" @back="navBack"
			>
		</order-header>
		<!-- 导航栏占位盒子 -->
		<!-- #ifdef APP-PLUS -->
		<view  :style="{height:  '240rpx',marginTop:statusBarHeight+'rpx'}"></view>
		<!-- #endif -->
		<!-- #ifndef APP-PLUS -->
		<view :style="{height:  '240rpx'}"></view>
		<!-- #endif -->
		<view class="u-p-l-30 u-p-t-30 u-p-r-30" >
			<!-- 卖家信息 -->
			<view class="u-p-l-35 u-p-r-35 u-p-t-30 u-p-b-30 u-m-b-20" style="background-color: #FFFFFF;" >
				<view class="u-font-bold u-font-28">{{info.sellerName}}</view>
				<view class="fui-oh__wrap">
					<fui-overflow-hidden :size="28" color="#FF2B2B" type="2" gradientColor="#FFFFFF"
						height="200rpx" :visible="visible">
						<view style="width: 100%;box-sizing: border-box;">
							<view class="u-flex u-m-t-10 u-row-between">
								<view class="u-font-28" style="font-weight: 500;">
									付款信息
								</view>
								<view class="u-font-28" style="color: #FF551A; font-weight: 500;">
									实付款￥{{info.totalAmount}}
								</view>
							</view>
							<view class="u-flex u-m-t-10 u-row-between">
								<view class="u-font-28" style="color: #999;">付款方式</view>
								<view class="u-font-28 u-text-right" style="color: #999;">{{payMethodStatus[info.paymentMethod]||'未发起支付'}}</view>
							</view>
							<view class="u-flex u-m-t-10 u-row-between">
								<view class="u-font-28" style="color: #999;">总金额</view>
								<view class="u-font-28 u-text-right" style="color: #999;">-￥{{info.originalPrice}}</view>
							</view>
							<view class="u-flex u-m-t-10 u-row-between">
								<view class="u-font-28" style="color: #999;">红包</view>
								<view class="u-font-28 u-text-right" style="color: #999;">-￥{{info.totalBalanceAmount}}</view>
							</view>
							<view class="u-flex u-m-t-10 u-row-between">
								<view class="u-font-28" style="color: #999;">活动</view>
								<view class="u-font-28 u-text-right" style="color: #999;">-￥{{info.totalPromotionAmount}}</view>
							</view>
							<sn-line color="#E5E5E5" class="u-m-t-20 u-m-b-20"/>
							<view class="u-flex u-m-t-10 u-row-between">
								<view class="u-font-28" style="color: #999;">订单数量</view>
								<view class="u-font-28 u-text-right" style="color: #999;">{{info.tradeQuantity}}</view>
							</view>
							<view class="u-flex u-m-t-10 u-row-between">
								<view class="u-font-28" style="color: #999;">明细数量</view>
								<view class="u-font-28 u-text-right" style="color: #999;">{{info.itemDetailsQuantity}}</view>
							</view>
							<view class="u-flex u-m-t-10 u-row-between">
								<view class="u-font-28" style="color: #999;">付款单编号</view>
								<view class="u-font-28 u-text-right" style="color: #999;">{{info.paymentNo}}</view>
							</view>
							<view class="u-flex u-m-t-10 u-row-between">
								<view class="u-font-28" style="color: #999;">创建时间</view>
								<view class="u-font-28 u-text-right" style="color: #999;">{{ $fui.dateFormatter(info.createdTime,'y-m-d h:i') }}</view>
							</view>
						</view>
					</fui-overflow-hidden>
					<view class="u-flex u-row-center" @click="readMore">
						<text class="u-font-24 u-font-grey">{{visibleText}}</text>
						<fui-icon :name="'arrowdown'" color="#999" size="32" :style="{transform:visible?'rotate(180deg)':'rotate(0deg)'}"></fui-icon>
						<!-- :style="{transform:visible?'ro':}" -->
					</view>
				</view>
			</view>
			<!-- 支付凭证 -->
			<view class="u-p-l-35 u-p-r-35 u-p-t-30 u-p-b-30 u-m-b-20" style="background-color: #FFFFFF;" 
			v-if="info.resourceIds.length!=0&&isPayment">
				<view class="u-font-32 u-m-b-30">付款凭证</view>
				<fui-upload immediate
					class="u-m-t-20"
					:file-list="fileList"
					:url="baseUrl + 'api/Resource/UploadToOss'"
					:header="header"
					:height="133"
					:width="'133rpx'"
					:max="maxPayResource"
					keepOne
					:isDel="info.paymentStatus<2"
					@success="e=>onSuccess(e,1)" 
					@delete="onRemove"
					>
				</fui-upload>
			</view>
			
			<!-- 新建订单 -->
			
			<view class="u-bg-white u-p-30">
				<view class="u-flex u-row-between">
					<text class="u-font-28 u-font-bold">订单明细</text>
					<view v-if="info.paymentStatus == 0&&isPayment" class="u-flex"  @click="addPayOrderFn">
						<fui-icon name="plussign-fill" size="38" color="#ff551a"></fui-icon>
						<text class="u-font-28 u-theme-main u-m-l-10">添加订单</text>
					</view>
				</view>
				
			</view>
			<!-- 订单详情列表 -->
			<fui-collapse  event-type="close"  @change="itemChange" :head-style="{'padding':0}" :accordion="false">
				<fui-collapse-item :index="index" :name="item.id" :arrow="false"  v-for="(item, index) in info.trades" :key="item.id" >
						<view class="u-p-l-35 u-p-r-35 u-p-t-30 u-p-b-30  u-flex u-row-between" slot="title-all" style="background-color: #fff;width: 100%;">
							<view class="">
								<view class="u-font-30" style="color: #333333;">{{item.tradeNo}}</view>
								<view class="u-m-t-10 u-m-b-10">
									<text class="u-font-24" style="color: #999999;">{{item.createdTime}}</text>
									<text class="u-font-24 " style="color: #FF551A;margin-left: 30rpx;">{{orderStatus[item.state]}}</text>
								</view>
								<view class="u-font-32" style="color: #FF551A;">￥{{item.actualAmount}}</view>
							</view>
							<view class="">
								<image src="/static/order/payorderDel.png" v-if="info.paymentStatus == 0&&isPayment" class="payorder-list-image u-m-r-40" @click.stop="showDelModel(item.id)"></image>
								<image src="/static/order/payorderOpen.png" :class="{'payorder-list-image':true,'payorder-list-image-active':openList[index]}" ></image>
							</view>
						</view>
						<template v-slot:content>
							<view class="collapse-item u-p-l-35 u-p-r-35 u-p-t-10 u-p-b-20" style="background-color: #FFFFFF;">
								<view class="u-flex u-row-between u-m-b-20" v-for="orderItem in item.items" :key="orderItem.id">
									<view class="u-flex u-col-top">
										<image :src="orderItem.url" mode="" style="width: 80rpx;height: 80rpx;"></image>
										<text class="u-font-28 u-m-l-20 u-line-1" style="width: 300rpx;">{{orderItem.itemName}}</text>
									</view>
									<view class="u-flex u-flex-wrap u-row-right" style="height: 100%;align-content: space-between;">
										<view class="u-font-28" style="color: #333;width: 100%;text-align: right;">￥{{orderItem.actuallyPrice}}</view>
										<view class="u-font-24 u-flex u-col-bottom  u-row-center" style="background-color: #F7F7F7;color: #999;padding: 7rpx 14rpx;">
											x{{orderItem.quantity}}
										</view>
									</view>
								</view>
								<view>
									<view class="u-flex u-m-t-16 u-row-between">
										<view class="u-font-28" style="color: #999;">总金额</view>
										<view class="u-font-28 u-text-right" style="color: #999;">￥{{item.amount}}</view>
									</view>
									<view class="u-flex u-m-t-10 u-row-between">
										<view class="u-font-28" style="color: #999;">红包</view>
										<view class="u-font-28 u-text-right" style="color: #999;">-￥{{item.balanceReduction}}</view>
									</view>
									<view class="u-flex u-m-t-10 u-row-between">
										<view class="u-font-28" style="color: #999;">活动</view>
										<view class="u-font-28 u-text-right" style="color: #999;">-￥{{item.promotionReduction}}</view>
									</view>
									<view class="u-flex u-m-t-10 u-row-between">
										<view class="u-font-30" style="color: #666;">折后金额</view>
										<view class="u-font-30 u-text-right" style="color: #666;">￥{{item.actualAmount}}</view>
									</view>
								</view>
							</view>
						</template>
					
				</fui-collapse-item>
			</fui-collapse>
		</view>
		<!-- 占位盒子 -->
		<view style="height: 160rpx;" v-if="isPayment"></view>
		<!-- 底部固定客服 -->
		<view class="footer u-flex" v-if="isPayment">
			<fui-button text="取消付款单" class="u-m-r-20" v-if="statusInfo.state <5" @click="modalShow = true" height="80rpx" width="100%" radius="45rpx" size="32" background="#F8F8F8" color="#999"></fui-button>
			<fui-button text="付款"  class="u-m-r-20" v-if="statusInfo.state == 0" @click="beforePayment"
			height="80rpx" width="100%" radius="45rpx" size="32" background="#FFECBF" color="#FFBB1A"></fui-button>
		</view>
		<fui-modal title="提示" :show="modalShow" :descr="modalContent" maskClosable @click="handleCancel" @cancel="modalShow = false"></fui-modal>
		<fui-modal title="提示" :show="delPayOrderShow" :descr="delContent" maskClosable  @cancel="delPayOrderShow = false" confirm-text="确定" cancel-text="取消" @click="delPayOrderFn" ></fui-modal>
		
		<fui-actionsheet  :itemList="payList" :show="payTypeShow" @click="handlePayment" maskClosable @cancel="payTypeShow = false;">
		</fui-actionsheet>
		<view v-html="alipayDom"></view>
	</view>
</template>
<script>
	import { useUserStore } from '@/store/user.js';
	import { useShopStore } from '@/store/shop.js';
	import { orderStore } from '@/store/order.js';
	import { mapState } from 'pinia';
	import OrderHeader from '@/components/order-header.vue';
	import snLine from '@/components/sn-line.vue';
	export default {
		components: {
			OrderHeader,snLine
		},
		data() {
			return {
				detailShow:false,
				id: null,
				alipayDom: '',
				modalShow: false,
				modalContent: '是否确认取消付款单',
				delPayOrderShow:false,
				delContent:'您是否确定将此订单从付款单中移除？',
				delOrderId:'',
				orderStatus:['待付款','待发货','待收货','待评价','已完成','已取消'],
				payMethodStatus:['微信支付','支付宝支付','银联支付','线下支付','线下支付'],
				info: {
					resourceIds:[]
				},
				state: 0,
				statusInfo: {},
				payTypeShow: false,
				paymentMethod: null,
				expire: '',
				expireTimer: undefined,
				isGoPay:false,
				loading:false,
				maxPayResource:1,
				delResource:false,
				payList:[],
				openList:[],
				offlineSet:{},
				fileList: [],
				routeFrom:"",
				routeOrderId:'',
				resourceList:[],
				visible:false,
				visibleText:'展开详情'
			}
		},
		computed:{
			...mapState(useUserStore,{
				isPurchase:'isPurchase',
				isPayment:'isPayment',
				header: (state)=>{
					Authorization: 'Bearer ' + state.user.access_token
				}
			}),
			...mapState(orderStore,['payorderStatus']),
			...mapState(useShopStore, {
				storeShop: 'shop',
			})	
		},
		async onLoad(options) {
			this.id = options.id;
			this.routeFrom = options.routeFrom;
			this.routeOrderId = options.orderId
			// if(options.paymentMethod!==undefined){
			// 	this.handlePayment('jiesuan',options.paymentMethod)
			// }
			await this.getOrderDetail()
		},
		
		onUnload() {
			clearInterval(this.expireTimer)
		},
		onShow() {
			if(this.isGoPay){
				this.$mRouter.redirectTo({
					route: '/pages/purchase/payorder/payresult?id=' + this.id
				})
			}
		},
		methods: {
			readMore() {
				if (this.visible) {
					this.visible = false
					this.visibleText = '展开详情'
				} else {
					this.visible = true
					this.visibleText = '收起详情'
				}
			},
			itemChange(data){
				this.$set(this.openList,data.index,data.isOpen)
			},
			async onSuccess(e) {
				let data = JSON.parse(e.res.data.replace(/\ufeff/g, "") || "{}")
				console.log(data);
				this.resourceList.push(data.data[0].id);
				let result = await this.offlineTradeChange();
				if(result){
					uni.$fui.toast('上传凭证成功');
					// this.resourceList.push(data.data[0].id);
				}else{
					uni.$fui.toast('上传凭证失败');
					this.getOrderDetail();
				}
			},
			async onRemove(data) {
				this.resourceList.splice(data,1);
				let result = await this.offlineTradeChange();
				if(result){
					uni.$fui.toast('删除凭证成功');
				}else{
					uni.$fui.toast('删除凭证失败');
					this.getOrderDetail()
				}
			},
			async offlineTradeChange(ary){
				this.loading = true;
				let res = await this.$newHttp.post('api/TradePayment/Pay', {
					id: this.info.id,
					paymentMethod: 3,
					resourceIds:this.resourceList
				});
				this.loading = false;
				try{
					if(res.code === 200){
						return true;
					}else{
						return false;
					}
				}catch(e){
					//TODO handle the exception
					return false;
				}
				
			},
			// 添加订单到付款单
			addPayOrderFn(){
				if (!this.isPayment) {
					return this.$u.toast('您没有操作付款单的权限')
				}
				let ary = [];
				this.info.trades.forEach(item=>{
					ary.push(item.id)
				})
				this.$mRouter.push({
					route: '/pages/purchase/payorder/createPayOrder?shop='+this.info.sellerId+'&payorderId='+this.info.id+'&trades='+JSON.stringify(ary),
				})
			},
			// 删除订单弹窗开启
			showDelModel(id){
				this.delPayOrderShow = true;
				this.delOrderId = id;
			},
			// 删除订单弹窗事件
			async delPayOrderFn(e){
				if(e.index ===1){
					this.loading = true;
					if(this.info.trades.length === 1){
						this.loading = false;
						uni.$fui.toast('最少需要有一个订单');
						return false;
					}
					let ary = [];
					this.info.trades.forEach(item=>{
						if(item.id!=this.delOrderId){
							ary.push(item.id)
						}
					});
					let params = {
						id:this.info.id,
						tradeIds:ary,
						isSeller:false,
						shopId:this.storeShop.id,
					}
					const res = await this.$newHttp.put('api/TradePayment/Update', params);
					this.loading = false;
					if(res.code === 200){
						this.getOrderDetail();
					}else{
						uni.$fui.toast(res.erroMessage);
					}
				}
				this.delPayOrderShow =false;
			},
			// 获取付款单详情
			async getOrderDetail() {
				this.loading = true;
				let params = {
					id: this.id,
					shopId:this.storeShop.id,
				}
				const res = await this.$newHttp.get('api/TradePayment/GetTradePaymentDetails', {params: params});
				this.loading = false;
				if(res.code == 200){
					this.info = res.data;
					this.statusInfo = this.payorderStatus.find(item => {
						return item.state == res.data.paymentStatus // 待付款
					});
					if(res.data.paymentMethod==3){
						if(res.data.resourceUrls.length != 0){
							this.fileList = res.data.resourceUrls;
							this.resourceList = res.data.resourceIds;
						}
						if(res.data.paymentStatus<2){
							this.maxPayResource =6;
							this.delResource = true;
						}else{
							this.maxPayResource = res.data.resourceIds.length;
							this.delResource = false;
						}
					}
					
				}else{
					uni.showToast({
						title:'获取付款单详情失败，错误信息：'+res.erroMessage
					})
				}
				
			},
			// 支付前判断
			async beforePayment() {
				if (!this.isPayment) {
					return this.$u.toast('您没有付款权限，请联系有付款权限的同事付款')
				}else{
					try{
						let res = await this.$http.get('api/Trade/GetContract',{ params: {
						buyerId: this.info.buyerId,
						sellerId:this.info.sellerId
					}});
						console.log(res);
						this.loading = false
						let payList = [];
						let offlineNo = 1;
						if(res){
							res.shopCollections.forEach((item,index)=>{
								if(item.shopCollectionType === 5){
									payList.push(
										{
											value: 0,
											text: '微信支付'
										})
								}
								if(item.shopCollectionType === 1){
									payList.push(
										{
											value: 11,
											text: '支付宝支付'
										})
								}
								if(item.shopCollectionType === 3){
									payList.push(
										{
											value: 3,
											text: '线下支付'+(offlineNo>1?offlineNo:''),
											bankOfDeposit:item.bankOfDeposit,
											accountNumber:item.accountNumber,
											accountName:item.accountName,
										});
										offlineNo++
								}
								if(item.shopCollectionType === 4){
									payList.push(
										{
											value: 4,
											text: '线下支付(月结)',
											bankOfDeposit:item.bankOfDeposit,
											accountNumber:item.accountNumber,
											accountName:item.accountName,
										})
								}
							});
							this.payList = payList;
							console.log(this.payList);
							this.payTypeShow = true
						}
					}catch(e){
						//TODO handle the exception
						console.log(e);
						this.loading = false
						uni.showToast({
							title:e
						})
					}
				}
				
			},
			async handleCancel(e) {
				if(e.index ===1){
					this.loading = true;
					const res = await this.$newHttp.delete('api/TradePayment/Cancel?id='+this.info.id);
					this.loading = false;
					if(res.code === 200){
						this.back();
					}else{
						uni.$fui.toast(res.erroMessage)
					}
				}
				this.modalShow = false;
			},
			async handlePayment(data) {
				let index = data.index;
				let paymentMethod = data.text;
				console.log(arguments);
				if(index === 'jiesuan'){
					this.paymentMethod = paymentMethod;
				}else{
					this.paymentMethod = this.payList[index].value;
				}
				// 微信app支付
				if (this.paymentMethod == 0) {
					// #ifdef  H5
					uni.showToast({
						title: '未开放H5微信支付'
					})
					// #endif
					// #ifdef APP-PLUS
					this.loading = true;
					let res = await this.$http.post('api/TradePayment/Pay', {
						id: this.id,
						paymentMethod: 0
					});
					this.loading = false;
					let that = this;
					let orderInfo = JSON.parse(res);
					uni.requestPayment({
						"provider": "wxpay",
						"orderInfo": JSON.parse(res),
						success: function(res) {
							console.log("支付成功");
							that.$mRouter.redirectTo({
								route: '/pages/purchase/payorder/payresult?id=' + that.id
							})
						},
						fail: function(err) {
							console.log('支付失败:' + JSON.stringify(err));
							that.$mRouter.redirectTo({
								route: '/pages/purchase/payorder/payresult?id=' + that.id
							})
						}
					});
					// #endif
				}
				// 支付宝app支付
				if (this.paymentMethod == 1) {
					// #ifdef  H5
					let res = await this.$http.post('api/TradePayment/Pay', {
						id: this.id,
						paymentMethod: 5
					});
					this.alipayDom = res;
					setTimeout(function() {
						document.forms['alipaysubmit'].submit();
					}, 500)
					// #endif
					// #ifdef APP-PLUS
					this.loading = true;
					let res = await this.$http.post('api/TradePayment/Pay', {
						id: this.id,
						paymentMethod: 6
					});
					this.loading = false;
					let orderInfo = res;
					let that = this;
					uni.requestPayment({
						"provider": "alipay", //固定值为"alipay"
						"orderInfo": orderInfo, //此处为服务器返回的订单信息字符串
						success: function(res) {
							console.log("支付成功");
							that.$mRouter.redirectTo({
								route: '/pages/purchase/payorder/payresult?id=' + that.id
							})
						},
						fail: function(err) {
							console.log('支付失败:' + JSON.stringify(err));
							that.$mRouter.redirectTo({
								route: '/pages/purchase/payorder/payresult?id=' + that.id
							})
						}
					});
					// #endif
				}
				if (this.paymentMethod == 3 || this.paymentMethod == 4) {
					this.offlineSet.id = this.id;
					this.offlineSet.sellerName = this.info.sellerName;
					this.offlineSet.paymentNo = this.info.paymentNo;
					this.offlineSet.actualAmount = this.info.totalAmount;
					this.offlineSet.paymentMethod = this.paymentMethod;
					this.offlineSet.bankOfDeposit = this.payList[index].bankOfDeposit;
					this.offlineSet.accountNumber = this.payList[index].accountNumber;
					this.offlineSet.accountName = this.payList[index].accountName;
					console.log(this.offlineSet);
					this.$mRouter.push({
						route: '/pages/cart/offline?offlineSet=' + JSON.stringify(this.offlineSet)
					})
				}
				// 支付宝当面付
				if (this.paymentMethod == 11) {
					this.loading = true;
					let res = await this.$http.post('api/TradePayment/Pay', {
						id: this.id,
						paymentMethod: 11
					});
					this.loading = false;
					let device = uni.getSystemInfoSync().platform;
					if (device === 'ios') {
						this.isGoPay = true;
						plus.runtime.openURL('alipay://platformapi/startapp?appId=20000067&url=' + encodeURIComponent(res))
					} else {
						this.isGoPay = true;
						plus.runtime.openURL('alipays://platformapi/startapp?appId=20000067&url=' + encodeURIComponent(res))
					}
				}
			},
			navBack(){
				console.log('触发back');
				let pages = getCurrentPages(); // 当前页面
				let beforePage = pages[pages.length - 2]; // 上一页
				if(beforePage.route === 'pages/purchase/order/details'){
					uni.navigateBack(); 
				}else{
					this.$mRouter.redirectTo({
						route: '/pages/purchase/payorder/index'
					})
				}
			},
			back() {
				if(this.routeFrom == 'order'){
					this.$mRouter.redirectTo({
						route: '/pages/purchase/order/details?id='+this.routeOrderId
					})
				}else{
					this.$mRouter.redirectTo({
						route: '/pages/purchase/payorder/index'
					})
				}
				
			}
		}
	}
</script>
<style lang="scss" scoped>
	.add-btn{
			width: 100rpx;
			height: 100rpx;
			background-color: #FFBB1A;
			margin-right: 30rpx;
			z-index: 11;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			box-shadow:  0rpx 0rpx 30rpx rgba(144,144,144,0.3);
		}
		.payorder-list-image{
			width: 42rpx;
			height: 42rpx;
			transition:transform .8s ;
		}
		.payorder-list-image-active{
			transform: rotateX(180deg);
			transition:transform .8s ;
		}
		.footer {
			position: fixed;
			bottom: 0;
			background-color: #FFFFFF;
			z-index: 9;
			width: 100%;
			height: 160rpx;
			padding: 0 30rpx;
		}
</style>
